package com.itheima.reggie.web.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//管理端员工的表现层控制器
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private HttpSession sqlSession;

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //获取请求参数
        String username = map.get("username");
        String password = map.get("password");
        //登录
        ResultInfo resultInfo = employeeService.login(username, password);

        //将登录标识存入会话域中
        if (resultInfo.getCode() == 1) {
            Employee employee = (Employee) resultInfo.getData();
            sqlSession.setAttribute(Constant.SESSION_EMPLOYEE, employee);
        }
        //返回结果
        return resultInfo;
    }

    //员工退出
    @PostMapping("/logout")
    public ResultInfo logout() {
        //清除登录信息
        sqlSession.invalidate();
        //返回成功
        return ResultInfo.success();
    }

    //查询员工列表
    @GetMapping("/find")
    public ResultInfo findAll(String name) {
        //调用service
        List<Employee> employeeList = employeeService.findByName(name);
        //返回成功
        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping
    public ResultInfo save(@RequestBody Employee employee) {
        //调用service
        employeeService.save(employee);
        //返回成功
        return ResultInfo.success();
    }

    //回显员工
    @GetMapping("/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        //调用service
        Employee employee = employeeService.findById(id);
        //返回成功
        return ResultInfo.success(employee);
    }

    //修改员工
    @PutMapping
    public ResultInfo update(@RequestBody Employee employee) {
        //调用service
        employeeService.update(employee);
        //返回成功
        return ResultInfo.success();
    }
}
